<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>视频上传</title>
    <script src="{{asset('js/jquery.min.js')}}"></script>
    <script src="{{asset('js/aliyun-upload-sdk-1.4.0/aliyun-upload-sdk-1.4.0.min.js')}}"></script>
    <script src="{{asset('js/aliyun-upload-sdk-1.4.0/lib/aliyun-oss-sdk-5.2.0.min.js')}}"></script>
    <script src="{{asset('js/aliyun-upload-sdk-1.4.0/lib/es6-promise.min.js')}}"></script>
</head>
<body>
<table frame=void width="100%" style="display:none;">
    <tr>
        <td>accessKeyId:</td>
        <td><input type="text" id="accessKeyId" size="20" value=""></td>
        <td>accessKeySecret:</td>
        <td><input type="text" id="accessKeySecret" size="40" value=""></td>
    </tr>
    <tr>
        <td>secretToken:</td>
        <td><input type="text" id="secretToken" size="40" value=""></td>
        <td></td>
        <td>点播STS参数如何获取，请查阅<a href=" https://help.aliyun.com/document_detail/28788.html?spm=a2c4g.11186623.2.6.1mSfTK" target="_blakn"> 获取STS</a></td>
    </tr>
    <tr>
        <td>endpoint:</td>
        <!-- oss-cn-shanghai.aliyuncs.com -->
        <!-- in-20170320144514766-hte7xhqk1t -->
        <!-- video/50659345-16127742b75-0004-a1f7-953-f8a30 -->
        <td><input type="text" id="endpoint" size="40" value=""></td>
        <td>bucket: </td>
        <td><input type="text" id="bucket" size="20" value=""></td>
    </tr>
    <tr>
        <td>object路径:</td>
        <td><input type="text" id="objectPre" size="20" value=""></td>

    </tr>
    <tr>
        <td></td>
        <td>以上相关参数如何获取，请查阅<a href="https://help.aliyun.com/document_detail/31867.html?spm=5176.doc31848.2.21.KS9R7q" target="_blakn"> OSS访问与控制文档</a></td>

    </tr>
</table>
<table frame=void width="70%">
    <tr>
        <td>视频标题:</td>
        <td><input type="text" id="video_title" size="20" value=""></td>
        <td>视频文件名（带后缀）:</td>
        <td><input type="text" id="video_name" size="30" value=""></td>
        <td>价格：</td>
        <td><input type="text" id="price" size="20" value=""/></td>
        <td>视频分类：</td>
        <td>
            <select name="cate" id="cate">
                <option value="">请选择</option>
                @foreach ($cate_list as $one_cate)
                <option value="{{ $one_cate->cate_id }}">{{ $one_cate->cate_name }}</option>
                @endforeach
            </select>
        </td>
        <td>封面图片</td>
        <td>
            <input type="file" name="picture" id="FileUpload"/>
        </td>
    </tr>
    <tr>
        <td>视频介绍</td>
        <td colspan="9">
            @include('UEditor::head')

            <div class="col-sm-10">
                <script id="ueditor" name="description"></script>
                <script>
                    ue = UE.getEditor("ueditor");
                    ue.ready(function () {
                        //由于Laravel有防csrf防伪造攻击的解决所以加上此行
                        ue.setHeight(400);
                        ue.execCommand('serverparam', '_token', '{{ csrf_token() }}');
                    });
                </script>
            </div>
        </td>
    </tr>
</table>
<script>
    $(function(){
        $("#video_name").blur(function(){
            let video_title = $("#video_title").val();
            let video_name = $("#video_name").val();
            /*let fileObj = document.getElementById("FileUpload").files[0]; // js 获取文件对象
            if (typeof (fileObj) === "undefined" || fileObj.size <= 0) {
                alert("请选择图片");
                return;
            }*/
            let formFile = new FormData();
            //formFile.append("file", fileObj); //加入文件对象
            formFile.append("video_title",video_title);
            formFile.append("video_name",video_name);
            formFile.append("_token","{{ csrf_token() }}");

            $.ajax({
                url:"/get_upload_address",
                type:"POST",
                data:formFile,
                dataType:"json",
                cache: false,
                processData: false,
                contentType: false,
                success:function(data){
                    $("#uploadAuth").val(data.uploadAuth);
                    $("#uploadAddress").val(data.uploadAddress);
                    $("#videoId").val(data.videoId);
                }
            });
        });
    });
</script>
<hr/>
<table frame=void width="100%" style="display:none;">
    <tr>
        <td><input type="hidden" id="uploadAuth" size="20" value=""></td>
        <td><input type="hidden" id="uploadAddress" size="20" value=""></td>
        <td><input type="hidden" id="videoId" size="20" value=""></td>
    </tr>
</table>

文件管理
<hr />
<input type="file" name="file" id="files" multiple/>
{{--<button type="button" onclick="clearInputFile()">清空继续选择</button>
<button type="button" onclick="deleteFile()">删除文件</button>
<input type="text" id="deleteIndex" size="3" value="0">
<button type="button" onclick="cancelFile()">取消文件</button>
<input type="text" id="cancelIndex" size="3" value="0">

<button type="button" onclick="resumeFile()">恢复文件</button>
<input type="text" id="resumeIndex" size="3" value="0">--}}
{{--<hr />
列表管理
<hr />
<button type="button" onclick="getList()">获取上传列表</button>
<button type="button" onclick="clearList()">清理上传列表</button>
<button type="button" onclick="getCheckpoint()">获取断点信息</button>
<hr />
上传管理--}}
<hr/>
<button type="button" onclick="start()">开始上传</button>
<button type="button" onclick="stop()">停止上传</button>
<!--  <button type="button" onclick="stop()">停止上传</button> -->
<button type="button" onclick="resumeWithToken()">token过期恢复上传</button>
<hr />
<select multiple="multiple" id="textarea" style="position:relative; width:90%; height:450px; vertical-align:top; border:1px solid #cccccc;"></select>
<button type="button" onclick="clearLog()">清日志</button>

<script>

    var accessKeyId = document.getElementById("accessKeyId").value;
    var accessKeySecret = document.getElementById("accessKeySecret").value;
    var secretToken = document.getElementById("secretToken").value;

    var uploader = new AliyunUpload.Vod({
        // 文件上传失败
        'onUploadFailed': function (uploadInfo, code, message) {
            log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message);
        },
        // 文件上传完成
        'onUploadSucceed': function (uploadInfo) {
            let formFile = new FormData();
            let video_title = $("#video_title").val();
            let video_id = $("#videoId").val();
            let cate = $("#cate").val();
            let description = ue.getContent();
            let price = $("#price").val();
            let picture = document.getElementById("FileUpload").files[0];
            formFile.append("video_title",video_title);
            formFile.append("video_id",video_id);
            formFile.append("cate_id",cate);
            formFile.append("description",description);
            formFile.append("price",price);
            formFile.append("picture",picture);
            formFile.append("_token","{{ csrf_token() }}");
            $.ajax({
                url:"/save_video_info",
                type:"POST",
                cache: false,
                processData: false,
                contentType: false,
                data:formFile,
                success:function(data){

                }
            });
            log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
        },
        // 文件上传进度
        'onUploadProgress': function (uploadInfo, totalSize, loadedPercent) {
            log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + (loadedPercent * 100.00).toFixed(2) + "%");
        },
        // STS临时账号会过期，过期时触发函数
        'onUploadTokenExpired': function (uploadInfo) {
            log("onUploadTokenExpired");
            if (isVodMode()) {
                // 实现时，根据uploadInfo.videoId从新获取UploadAuth
                //实际环境中调用点播的刷新上传凭证接口，获取凭证
                //https://help.aliyun.com/document_detail/55408.html?spm=a2c4g.11186623.6.630.BoYYcY
                //获取上传凭证后，调用setUploadAuthAndAddress
                // uploader.resumeUploadWithAuth(uploadAuth);
            } else if (isSTSMode()) {
                // 实现时，从新获取STS临时账号用于恢复上传
                // uploader.resumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken, expireTime);
            }
        },
        onUploadCanceled:function(uploadInfo)
        {
            log("onUploadCanceled:file:" + uploadInfo.file.name);
        },
        // 开始上传
        'onUploadstarted': function (uploadInfo) {
            if (isVodMode()) {
                if(!uploadInfo.videoId)//这个文件没有上传异常
                {
                    //mock 上传凭证，实际产品中需要通过接口获取
                    var uploadAuth = document.getElementById("uploadAuth").value;
                    var uploadAddress = document.getElementById("uploadAddress").value;
                    var videoId = document.getElementById("videoId").value;
                    //实际环境中调用调用点播的获取上传凭证接口
                    //https://help.aliyun.com/document_detail/55407.html?spm=a2c4g.11186623.6.629.CH7i3X
                    //获取上传凭证后，调用setUploadAuthAndAddress
                    uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId);
                }
                else//如果videoId有值，根据videoId刷新上传凭证
                {
                    //mock 上传凭证 实际产品中需要通过接口获取
                    var uploadAuth = document.getElementById("uploadAuth").value;
                    var uploadAddress = document.getElementById("uploadAddress").value;
                    //实际环境中调用点播的刷新上传凭证接口，获取凭证
                    //https://help.aliyun.com/document_detail/55408.html?spm=a2c4g.11186623.6.630.BoYYcY
                    //获取上传凭证后，调用setUploadAuthAndAddress
                    uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress);
                }
            }
            else if (isSTSMode()) {
                var accessKeyId = document.getElementById("accessKeyId").value;
                var accessKeySecret = document.getElementById("accessKeySecret").value;
                var secretToken = document.getElementById("secretToken").value;
                uploader.setSTSToken(uploadInfo, accessKeyId, accessKeySecret,secretToken);
            }
            log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
        }
        ,
        'onUploadEnd':function(uploadInfo){
            log("onUploadEnd: uploaded all the files");
        }
    });

    var getCheckpoint = function()
    {
        var list = uploader.listFiles();
        for (var i=0; i<list.length; i++) {
            var value = uploader.getCheckpoint(list[i].file);
            if(value)
            {
                log(list[i].file.name + ' checkpoint: videoId=' + value.videoId + ' loaded='+value.loaded + ' state=' + value.state);
            }
            else
            {
                log(list[i].file.name + ' no checkpoint.');
            }
        }
    }

    // 点播上传。每次上传都是独立的鉴权，所以初始化时，不需要设置鉴权
    // 临时账号过期时，在onUploadTokenExpired事件中，用resumeWithToken更新临时账号，上传会续传。
    var selectFile = function (event) {
        var endpoint = document.getElementById("endpoint").value;
        var bucket = document.getElementById("bucket").value;
        var objectPre = document.getElementById("objectPre").value;
        var userData;
        if (isVodMode()) {
            userData = '{"Vod":{"StorageLocation":"","UserData":{"IsShowWaterMark":"false","Priority":"7"}}}';
        } else {
            userData = '{"Vod":{"StorageLocation":"","Title":"this is title.我是标题","Description":"this is desc.我是描述","CateId":"19","Tags":"tag1,tag2,标签3"}}';
        }

        for(var i=0; i<event.target.files.length; i++) {
            log("add file: " + event.target.files[i].name);
            if (isVodMode()) {
                // 点播上传。每次上传都是独立的OSS object，所以添加文件时，不需要设置OSS的属性
                uploader.addFile(event.target.files[i], null, null, null, userData);
            } else if(isSTSMode()) {
                // STS的上传方式，需要在userData里指定Title
                var object = objectPre;
                // if(objectPre)
                // {
                //     object = objectPre +"/"+ event.target.files[i].name;
                // }
                uploader.addFile(event.target.files[i], endpoint, bucket, object , userData);
            }
        }
    };

    document.getElementById("files")
        .addEventListener('change', selectFile);

    var textarea=document.getElementById("textarea");

    function start() {
        log("start upload.");
        uploader.startUpload();
    }

    function stop() {
        log("stop upload.");
        uploader.stopUpload();
    }

    function resumeWithToken() {
        log("resume upload with token.");
        var uploadAuth = document.getElementById("uploadAuth").value;

        var accessKeyId = document.getElementById("accessKeyId").value;
        var accessKeySecret = document.getElementById("accessKeySecret").value;
        var secretToken = document.getElementById("secretToken").value;

        if (isVodMode()) {
            uploader.resumeUploadWithAuth(uploadAuth);
        } else if (isSTSMode()) {
            uploader.resumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken);
        }
    }

    function clearInputFile()
    {
        var ie = (navigator.appVersion.indexOf("MSIE")!=-1);
        if( ie ){
            var file = document.getElementById("files");
            var file2= file.cloneNode(false);
            file2.addEventListener('change', selectFile);
            file.parentNode.replaceChild(file2,file);
        }
        else
        {
            document.getElementById("files").value = '';
        }

    }

    function clearList() {
        log("clean upload list.");
        uploader.cleanList();
    }

    function getList() {
        log("get upload list.");
        var list = uploader.listFiles();
        for (var i=0; i<list.length; i++) {
            log("file:" + list[i].file.name + ", status:" + list[i].state + ", endpoint:" + list[i].endpoint + ", bucket:" + list[i].bucket + ", object:" + list[i].object);
        }
    }

    function deleteFile() {
        if (document.getElementById("deleteIndex").value) {
            var index = document.getElementById("deleteIndex").value
            log("delete file index:" + index);
            uploader.deleteFile(index);
        }
    }

    function cancelFile() {
        if (document.getElementById("cancelIndex").value) {
            var index = document.getElementById("cancelIndex").value
            log("cancel file index:" + index);
            uploader.cancelFile(index);
        }
    }

    function resumeFile() {
        if (document.getElementById("resumeIndex").value) {
            var index = document.getElementById("resumeIndex").value
            log("resume file index:" + index);
            uploader.resumeFile(index);
        }
    }

    function clearLog() {
        textarea.options.length = 0;
    }

    function log(value) {
        if (!value) {
            return;
        }

        var len = textarea.options.length;
        if (len > 0 && textarea.options[len-1].value.substring(0, 40) == value.substring(0, 40)) {
            //textarea.remove(len-1);
        } else if (len > 25) {
            textarea.remove(0);
        }

        var option=document.createElement("option");
        option.value=value,option.innerHTML=value;
        textarea.appendChild(option);
    }

    function isVodMode() {
        var uploadAuth = document.getElementById("uploadAuth").value;
        return (uploadAuth && uploadAuth.length > 0);
    }

    function isSTSMode() {
        var secretToken = document.getElementById("secretToken").value;
        if (!isVodMode()) {
            if (secretToken && secretToken.length > 0) {
                return true;
            }
        }
        return false;
    }

</script>

</body>
</html>
